import React, { useRef, useState, useMemo } from 'react';
import { Button, Tabs, Card, Col, Row, Switch, Tag, Space, Input, message } from 'antd';
import { useSelector, useDispatch } from 'react-redux';
import { changeactiveKey, addtypelists, deltypelist } from '../../store/crmsSlice';

//分类列表组件
const TypeList = () => {

  //获取rtk状态
  let obj = useSelector(state => state.crms1)
  let dispatch = useDispatch()
  console.log(obj);

  //过滤出typeId一致的商品列表
  let newlist = useMemo(() => {
    return obj.shoplist.filter(item => {
      return item.typeId == obj.activeKey
    })
  }, [obj.shoplist, obj.activeKey])

  //输入框输入的值
  let [title, setTitle] = useState('')

  //切换高亮
  const onChange = key => {
    //执行切换高亮的同步方法
    dispatch(changeactiveKey(key))
  };
  //添加
  const add = () => {
    //输入分类内容不能为空
    if (!title) {
      message.open({
        type: 'warning',
        content: '分类内容不能为空',
      });
      return
    }
    let t = new Date().getTime()
    let obj = {
      "id": t,
      "key": t,
      "typeId": t,
      "label": title
    }
    //添加数据的方法
    dispatch(addtypelists(obj))
    //清除输入框
    setTitle('')
  };
  //删除
  const remove = targetKey => {
    //如果分类中有商品列表 不能被删除
    //some遍历数组 查找是否都符合 返回的条件 有一个符合条件的返回true 没有符合条件的返回false
    let falg = obj.shoplist.some(item => {
      return item.typeId == targetKey
    })
    if (falg) {
      message.open({
        type: 'warning',
        content: '分类中有商品列表,不能删除',
      });
      return 
    }
    //执行删除的分类
    dispatch(deltypelist(targetKey))
  };
  //不管添加和删除 都执行
  const onEdit = (targetKey, action) => {
    if (action === 'add') {
      add();
    } else {
      remove(targetKey);
    }
  };
  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Input style={{ width: '300px' }} value={title} onChange={(e) => {
          setTitle(e.target.value)
        }} />
        <Button onClick={add} type='primary' style={{ marginLeft: '5px' }}>添加</Button>
      </div>
      <Tabs

        hideAdd
        onChange={onChange}
        activeKey={obj.activeKey}
        type="editable-card"
        onEdit={onEdit}
        items={obj.typelist}
      />
      <div>
        <Row gutter={16}>
          {
            newlist.map(item => {
              return <Col span={6} key={item.id} style={{ marginBottom: '10px' }}>
                <Card title={item.title} variant="borderless" extra={<span>删除</span>}>
                  <div>价格:￥{item.price}</div><br />
                  <div>
                    状态:<Switch checked={item.Collect} onChange={() => { }} />
                  </div><br />
                  <div>
                    <Space>
                      规格:{item.specification.map(ele => {
                        return <Tag key={ele} color='green'>{ele}</Tag>
                      })}
                    </Space>
                  </div>
                </Card>
              </Col>
            })
          }
        </Row>

      </div>
    </div>
  );
};
export default TypeList;
